package jeesample.secured.jaxrs;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;

import jeesample.dtos.EchoDTO;
import jeesample.jaxrs.BaseRESTfulService;
import jeesample.service.publishers.EchoServicePublisher;

import org.apache.log4j.Logger;

@Path("secured/echo")
public class EchoRS extends BaseRESTfulService {
	private Logger logger = Logger.getLogger(getClass());

	@Override
	protected Logger logger() {
		return logger;
	}

	private EchoServicePublisher publisher = new EchoServicePublisher();

	@GET
	@Path("/ping/{userId}")
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public EchoDTO ping(@PathParam("userId") final String userId,
			@Context UriInfo uriInfo, @Context HttpServletRequest request,
			@Context SecurityContext securityContext) {

		dbg("secure ping(" + userId + ")");

		StringBuilder sb = new StringBuilder();
		sb.append("\nAuthentication Scheme:");
		sb.append(securityContext.getAuthenticationScheme());
		sb.append("\nUser Principal:");
		Principal principal = request.getUserPrincipal();
		if (principal != null) {
			sb.append(principal.getName());
		}

		sb.append("\nPing info:");
		sb.append(publisher.ping(userId));

		EchoDTO dto = new EchoDTO(sb.toString());
		dto.fill(uriInfo);
		dto.fill(request);
		dto.fill(securityContext);
		return dto;
	}
}
